import { Component, OnInit } from '@angular/core';
import {CamRecordService} from "../../shared/service/cam-record.service";
import {Application} from "../../shared/model/application";
import {ActivatedRoute} from "@angular/router";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {CamSearchService} from "../../shared/service/cam-search.service";
import {Condition} from "../../shared/model/condition";
import {CamManageService} from "../../shared/service/cam-manage.service";

@Component({
  selector: 'app-cam-record-table',
  templateUrl: './cam-record-table.component.html',
  styleUrls: ['./cam-record-table.component.css']
})
export class CamRecordTableComponent implements OnInit {
  applicant :string = ""; //申请人员（普通员工默认为登录者自己，车辆管理员可以选择）;
  starttime:string = "";  //开始时间
  endtime:string = "";  //结束时间
  userId:string = this.routeInfo.snapshot.queryParams["userId"];     //当前登陆者ID
  selectedData = [];
  status:number = -1;       //用车申请状态  0：审批中（流程进行中）；1：已审批（流程正常结案）；2：已撤销（申请人操作）；3：已终止（审批人操作） 4：取消（结案之后，派车之前，申请人可以取消出车申请）'
  applicationList:Application[]=[];
  vehicleOid:string="";
  allCheckbox:boolean = false;
  _dataSet = [];
  _total = 1;
  _current = 1;
  _pageSize = 10;
  _loading = true;
  //选择框
  _allChecked = false;
  _displayData: Array<any> = [];
  _checkedNumber = 0;
  _checkInfo= [];
  checkAllInfo = [];

  constructor(private camRecordService:CamRecordService,
              private routeInfo:ActivatedRoute,
              private singleOpenWinService:SingleOpenWinService,
              private camSearchService:CamSearchService,
              private camManageService:CamManageService ) {
  }

  ngOnInit() {
    this.singleOpenWinService.oidChange.subscribe(info=>{
      this.vehicleOid=info;
      this.refreshData();
    })
    this.camSearchService.change.subscribe((info:Condition)=>{
      this.getCondition(info);
      this.refreshData();
    });
  }


  //参数传递赋值
  getCondition(condition:Condition){
    this.userId = condition.userId;
    this.applicant = condition.applicant;
    this.status = condition.status;
    this.starttime = condition.starttime;
    this.endtime = condition.endtime;
  }


  //根据车辆，查询所有用车记录
  getCamApplyInfoByVehicle(){
    let exclude = "";
    if(this.status == -1){
      exclude = "2,3";
    }else if(this.status == 0){
      exclude = "1,2,3,4";
    }else if(this.status == 1){
      exclude = "0,2,3,4";
    }else if(this.status == 2){
      exclude = "0,1,3,4";
    }else if(this.status == 3){
      exclude = "0,1,2,4";
    }else if(this.status == 4){
      exclude = "0,2,3,1";
    }
    if(typeof (this.applicant)==="undefined"){
      this.applicant="";
    }
    if(this.vehicleOid) {
      this.camRecordService.getCamApplyInfoByVehicle(this._current, this._pageSize, this.applicant, this.vehicleOid, exclude).then(res => {
        this.applicationList = res.list;
        this.allCheckbox = false;
        for (let i = 0; i < this.applicationList.length; i++) {
          //判断用车记录状态
          let statusname = "";
          let date = new Date();
          this.applicationList[i].cancel = false;
          switch (this.applicationList[i].status) {
            case 0:
              statusname = "审批中";
              break;
            case 1:
              statusname = "已审批";
              if (date < new Date(this.applicationList[i].starttime)) {
                this.applicationList[i].cancel = true;
              }
              break;
            case 2:
              statusname = "已撤销";
              break;
            case 3:
              statusname = "已终止";
              break;
            case 4:
              statusname = "已取消";
              break;
          }
          this.applicationList[i].statusname = statusname;
          //判断全选框是否显示
          if (this.applicationList[i].status != 0 && this.applicationList[i].status != 1) {
            this.allCheckbox = true;
          }
        }
        this._dataSet = res.list;
        this._loading = false;
        this._total = res.total;
        this._displayData = res.list;
        //查询选中
        for (var i = 0; i < this._checkInfo.length; i++) {
          if (this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1) {
            this.checkAllInfo.push(this._checkInfo[i].oid);
          }
        }
        //选择判断
        this.select(this.checkAllInfo, this._dataSet);

        //全选判断
        this._refreshStatus("", "");

      })
    }

  }

  refreshData(reset = false){
    if (reset) {
      this._current = 1;
    }
    this._loading = true;
    this.getCamApplyInfoByVehicle();
  }

  _displayDataChange($event) {
    this._displayData = $event;
  };

  _checkAll(value) {
    if (value) {
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status!=0&&this._displayData[i].status!= 1){
          this._displayData[i].checked = true;
        }
      }
    } else {
      this._displayData.forEach(data => data.checked = false);
      for(let i=0;i<this._displayData.length;i++){
        let numb = this.checkAllInfo.indexOf(this._displayData[i].oid);
        if(numb!=-1){
          this.checkAllInfo.splice(numb,1);
        }
      }
    }
    this._refreshStatus("","");
  };

  //当前页checkbox选中判断
  _refreshStatus(event,oid) {
    //全选判断
    if(this._displayData.length>0){
      let count:number = 0;
      let checkNumb:number = 0;
      for(let i =0;i<this._displayData.length;i++){
        if(this._displayData[i].status !=0&&this._displayData[i].status != 1){
          count++;
          if(this._displayData[i].checked == true){
            checkNumb++;
          }
        }
      }
      if(checkNumb!=0 && count==checkNumb){
        this._allChecked = true;
      }else{
        this._allChecked = false;
      }
    }
    this._checkedNumber = this._dataSet.filter(value => value.checked).length;
    this._checkInfo = this._dataSet.filter(value => value.checked);  //存放选中行的信息
    //判断是否有checkbox取消事件
    if(event==false){
      let numb = this.checkAllInfo.indexOf(oid);
      if(numb!=-1){
        this.checkAllInfo.splice(numb,1);
      }
    }
  };

  //选择判断
  select(selectedData:any,currentData:any){
    let selectInfo = [];
    if(selectedData){
      for(var i=0;i<currentData.length;i++){
        for(var j=0;j<selectedData.length;j++){
          if(currentData[i].oid == selectedData[j]){
            selectInfo.push(currentData[i]);
          }
        }
      }
      selectInfo.forEach(data => data.checked = true);
    }
  }

  //删除出车记录
  delInfo(){
    //将当前页所选会议信息插入所有选择信息变量checkAllInfo中
    for(var i=0;i<this._checkInfo.length;i++){
      if(this.checkAllInfo.indexOf(this._checkInfo[i].oid) == -1){
        this.checkAllInfo.push(this._checkInfo[i].oid);
      }
    }
    if(this.checkAllInfo.length>0){
      if(confirm("共选择"+this.checkAllInfo.length+"条出车记录，删除后将无法恢复，确定要删除吗？\n")){
        for(let i=0;i<this.checkAllInfo.length;i++){
          this.camRecordService.deleteApplication(this.checkAllInfo[i]);
        }
        alert("删除成功！\n");
        this.checkAllInfo = [];
        this._checkInfo = [];
        this._current = 1;
        this.refreshData();
      }
    }else{
      alert("请至少选择一条出车记录！\n");
    }
  }
}
